package com.lfb.network.tcp;

import java.io.BufferedReader;
import java.io.BufferedWriter;
import java.io.IOException;
import java.io.OutputStreamWriter;
import java.net.Socket;
import java.net.UnknownHostException;

public class ClientThread implements Runnable {
    //服务器主机的IP地址
    private String hostIp;
    /**
     * 服务器主机socket通信所监听的端口号
     * 客户端与服务器端的端口号需要保持一致
     */
    private int port;

    public ClientThread(String hostIp, int port) {
        this.hostIp = hostIp;
        this.port = port;
    }

    @Override
    public void run() {
        try {
            /******************客户端使用输出流发送信息****************/
            //创建一个Socket客户端对象
            Socket socket = new Socket(hostIp, port);
            //获取客户端的输出流对象
            BufferedWriter bw = new BufferedWriter(new OutputStreamWriter(socket.getOutputStream(),"UTF-8"));
            //客户端发送的信息
            String strM_c = "你好，我是客户端";
            //将消息数据流通过网络发送出去
            bw.write(strM_c);
            //应为writer没有行结束符
            bw.write("\n");
            //清空缓存
            bw.flush();
            //输出信息
            System.out.println("客户端发送信息：" + strM_c);
            //关闭资源
            //bw.close();
        }catch (UnknownHostException e){
            e.printStackTrace();
        }catch (IOException e) {
            e.printStackTrace();
        }
    }
}
